<template>
  <div class="ticket-management">
    <div class="header">
      <h1>门票管理</h1>
      <el-button type="primary" @click="handleAdd">新增门票</el-button>
    </div>

    <!-- 查询区域 -->
    <div class="filter-bar"
      style="margin-bottom: 18px; background: #fff; padding: 16px; border-radius: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.04); display: flex; gap: 24px; align-items: center;">
      <el-form :inline="true" :model="filter" label-width="80px">
        <el-form-item label="景区名称">
          <el-input v-model="filter.sightName" placeholder="请输入景区名称" clearable style="width: 160px;" />
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input v-model.number="filter.priceMin" placeholder="最低价" type="number" style="width: 90px;" />
          <span style="margin: 0 8px;">-</span>
          <el-input v-model.number="filter.priceMax" placeholder="最高价" type="number" style="width: 90px;" />
        </el-form-item>
        <el-form-item label="库存区间">
          <el-select v-model="filter.stockRange" placeholder="全部库存" clearable style="width: 140px;">
            <el-option label="0-99" value="0-99" />
            <el-option label="100-299" value="100-299" />
            <el-option label="300以上" value="300+" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="handleResetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table :data="ticketList" style="width: 100%" border size="medium" :header-cell-style="{ fontWeight: 'bold' }"
        :cell-style="{ height: '60px' }">
        <el-table-column prop="ticketId" label="门票ID" width="100" align="center" />
        <el-table-column label="景区名称" width="180" align="center">
          <template #default="scope">
            {{ getSightNameById(scope.row.sightId) || '未知景区' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格￥" width="100" align="center" />
        <el-table-column label="库存" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStockTagType(scope.row.stock)" size="small">
              {{ scope.row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ticketType" label="门票类型" width="120" align="center">
          <template #default="scope">
            {{ ticketTypeMap[scope.row.ticketType] || scope.row.ticketType }}
          </template>
        </el-table-column>
        <el-table-column prop="sourceChannel" label="票源渠道" width="120" align="center">
          <template #default="scope">
            {{ sourceChannelMap[scope.row.sourceChannel] || scope.row.sourceChannel }}
          </template>
        </el-table-column>
        <el-table-column prop="saleStartTime" label="开售时间" width="160" align="center">
          <template #default="scope">
            {{ scope.row.saleStartTime ? formatDate(scope.row.saleStartTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="saleEndTime" label="停售时间" width="160" align="center">
          <template #default="scope">
            {{ scope.row.saleEndTime ? formatDate(scope.row.saleEndTime) : '长期售卖' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="门票状态" width="100" align="center">
          <template #default="scope">
            {{ statusMap[scope.row.status] || scope.row.status }}
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="购票须知" min-width="200" align="left" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="formData" label-width="90px">
        <el-form-item label="景区名称" prop="sightId" :rules="[{ required: true, message: '请选择景区', trigger: 'blur' }]">
          <el-select v-model.number="formData.sightId" placeholder="请选择景区">
            <el-option v-for="sight in sightList" :key="sight.sightId" :label="sight.name" :value="sight.sightId" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="formData.price" placeholder="请输入价格" type="number" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model.number="formData.stock" placeholder="请输入库存" type="number" />
        </el-form-item>
        <el-form-item label="门票类型">
          <el-select v-model="formData.ticketType" placeholder="请选择门票类型">
            <el-option v-for="(label, value) in ticketTypeMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="票源渠道">
          <el-select v-model="formData.sourceChannel" placeholder="请选择票源渠道">
            <el-option v-for="(label, value) in sourceChannelMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开售时间">
          <el-date-picker v-model="formData.saleStartTime" type="datetime" placeholder="选择开售时间" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="停售时间">
          <el-date-picker v-model="formData.saleEndTime" type="datetime" placeholder="选择停售时间（可为空）"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="门票状态">
          <el-select v-model="formData.status" placeholder="请选择门票状态">
            <el-option v-for="(label, value) in statusMap" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="购票须知">
          <el-input v-model="formData.desc" placeholder="请输入购票须知" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 字典映射
const ticketTypeMap = {
  adult: '成人票',
  child: '儿童票',
  student: '学生票',
  senior: '老人票',
  group: '团体票'
}
const sourceChannelMap = {
  official: '官方平台',
  third_party: '第三方平台',
  agent: '代理商',
  offline: '线下窗口'
}
const statusMap = {
  active: '可售卖',
  inactive: '未激活',
  sold_out: '售罄',
  stopped: '已停售'
}

// 时间格式化
function formatDate(dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return d.toLocaleString()
}
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTickets, addTicket, updateTicket, deleteTicket } from '@/views/api/ticket'
import { getSightList } from '@/views/api/sight'

// 数据列表
const ticketList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 景区列表
const sightList = ref([])

// 查询条件
const filter = reactive({
  sightName: '', // 新增景区名称模糊搜索
  priceMin: '',
  priceMax: '',
  stockRange: '' // "0-99", "100-299", "300+"
})

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增门票')
const formData = reactive({
  ticketId: null,
  sightId: '',
  price: '',
  stock: '',
  ticketType: 'adult',
  sourceChannel: 'official',
  saleStartTime: '',
  saleEndTime: '',
  status: 'active',
  desc: ''
})

// 重置表单
const resetForm = () => {
  formData.ticketId = null
  formData.sightId = ''
  formData.price = ''
  formData.stock = ''
  formData.ticketType = 'adult'
  formData.sourceChannel = 'official'
  formData.saleStartTime = ''
  formData.saleEndTime = ''
  formData.status = 'active'
  formData.desc = ''
}

// 获取景区列表
const getSights = async () => {
  try {
    const response = await getSightList()
    // 确保sightList是数组类型
    if (response.data && response.data.data && Array.isArray(response.data.data.items)) {
      // 正确处理API返回的数据结构: data.data.items
      sightList.value = response.data.data.items
    } else if (response.data && Array.isArray(response.data.data)) {
      // 处理可能的分页结构
      sightList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      sightList.value = response.data
    } else {
      console.warn('景区数据格式不符合预期:', response)
      sightList.value = []
    }
  } catch (error) {
    ElMessage.error('获取景区列表失败')
    console.error('获取景区列表失败:', error)
    sightList.value = []
  }
}

// 根据景区ID获取景区名称
const getSightNameById = (id) => {
  // 安全检查，确保sightList是数组
  if (!Array.isArray(sightList.value)) {
    console.warn('sightList不是有效的数组')
    return '未知景点'
  }
  // 根据API返回的实际字段名进行匹配 (sightId)
  const sight = sightList.value.find(item => item.sightId === id)
  return sight ? sight.name : '未知景点'
}

// 根据库存数量返回对应的标签类型
const getStockTagType = (stock) => {
  if (stock >= 100) {
    return 'success'; // 绿色
  } else if (stock >= 50) {
    return 'warning'; // 橙色
  } else {
    return 'danger'; // 红色
  }
};

// 获取门票列表（带筛选条件）
const getTicketList = async () => {
  try {
    // 构造查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    if (filter.sightName && filter.sightName.trim() !== '') params.sightName = filter.sightName.trim()
    if (filter.priceMin !== '' && filter.priceMin !== null) params.priceMin = filter.priceMin
    if (filter.priceMax !== '' && filter.priceMax !== null) params.priceMax = filter.priceMax
    if (filter.stockRange) {
      if (filter.stockRange === '0-99') {
        params.stockMin = 0
        params.stockMax = 99
      } else if (filter.stockRange === '100-299') {
        params.stockMin = 100
        params.stockMax = 299
      } else if (filter.stockRange === '300+') {
        params.stockMin = 300
      }
    }
    const response = await getTickets(params)
    ticketList.value = response.data.data.list || []
    total.value = response.data.data.total || 0
  } catch (error) {
    ElMessage.error('获取门票列表失败')
    console.error('获取门票列表失败:', error)
  }
}

// 查询按钮
const handleFilter = () => {
  currentPage.value = 1
  getTicketList()
}

// 重置查询条件
const handleResetFilter = () => {
  filter.sightName = ''
  filter.priceMin = ''
  filter.priceMax = ''
  filter.stockRange = ''
  currentPage.value = 1
  getTicketList()
}

// 新增门票
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增门票'
  dialogVisible.value = true
}

// 编辑门票
const handleEdit = (row) => {
  // 深拷贝行数据以避免直接修改原始数据
  const rowData = { ...row }
  // 确保sightId是数字类型，与option的value类型匹配
  rowData.sightId = Number(rowData.sightId)
  Object.assign(formData, rowData)
  dialogTitle.value = '编辑门票'
  dialogVisible.value = true
}

// 删除门票
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除门票ID为 ${row.ticketId} 的门票吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteTicket(row.ticketId)
    ElMessage.success('删除成功')
    getTicketList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除门票失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (formData.replyToUserId === '') {
      formData.replyToUserId = null;
    }
    if (formData.ticketId) {
      // 编辑操作
      await updateTicket(formData.ticketId, formData)
      ElMessage.success('更新成功')
    } else {
      // 新增操作
      await addTicket(formData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getTicketList()
  } catch (error) {
    ElMessage.error(formData.ticketId ? '更新失败' : '新增失败')
    console.error('提交表单失败:', error)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getTicketList()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  getTicketList()
}

// 初始加载数据
onMounted(async () => {
  // 先获取景区列表，再获取门票列表
  await getSights()
  getTicketList()
})
</script>

<style scoped>
.ticket-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 增强表格样式 */
:deep(.el-table) {
  border: 0.5px solid #e8e8e8;
}

:deep(.el-table__header th.el-table__cell) {
  border-right: 0.5px solid #e8e8e8;
  border-bottom: 0.5px solid #e8e8e8;
}

:deep(.el-table__body td.el-table__cell) {
  border-right: 0.5px solid #e8e8e8;
  border-bottom: 0.5px solid #f0f0f0;
  padding: 12px 8px;
}

:deep(.el-table__body tr:hover > td.el-table__cell) {
  background-color: #f5f7fa;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.filter-bar {
  /* 见 template 行内样式 */
}
</style>